﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Article
{
    public class Article_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Article/article_list.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;
        protected int category_id;
        protected int channel_id;
        protected string property = string.Empty;
        protected string keywords = string.Empty;
        protected string prolistview = string.Empty;
        public IArticleService _article { get; set; }
        public IArticle_categoryService _article_category { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            this.channel_id = CMSRequest.GetQueryInt("channel_id", filterContext.HttpContext);
            ChkAdminLevel("article_"+ this.channel_id + "_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ActionResult result = View(EDIT_RESULT_VIEW);
            
            int.TryParse(Request.Query["category_id"], out this.category_id);
            this.keywords = Request.Query["keywords"];
            this.property = Request.Query["property"];
            int.TryParse(Request.Query["pagesize"], out this.pageSize);
            this.prolistview = Request.Query["prolistview"];            
            int.TryParse(Request.Query["page"],out this.page);
            if (this.prolistview != null)
            {
                Response.Cookies.Append("article_list_view", this.prolistview);
            }
            else
            {
                this.prolistview = Request.Cookies["article_list_view"]; //显示方式                
            }
            if (string.IsNullOrEmpty(this.prolistview))
            {
                this.prolistview = "Txt";
            }
            if (this.pageSize > 0)
            {
                if (this.pageSize != GetPageSize(10))
                    Response.Cookies.Append("article_page_size", this.pageSize.ToString());
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }

            //保存参数
            ViewBag.ChannelId = this.channel_id.ToString();
            ViewBag.CategoryId = this.category_id.ToString();
            ViewBag.Keywords = this.keywords;
            ViewBag.Property = this.property;
            ViewBag.ProListView = this.prolistview;
            ViewBag.PageSize = this.pageSize.ToString();
            ViewBag.Page = this.page.ToString();
        }
        //
        // GET: /admin/Article_List/

        public ActionResult Index()
        {
            TreeBind(); //绑定类别
            RptBind(this.category_id, "where channel_id="+this.channel_id + CombSqlTxt(this.keywords, this.property), "sort_id asc,add_time desc,id desc");
            return View(WEB_VIEW);
        }

        //设置文章状态
        [HttpPost]
        public ActionResult SetStatus()
        {
            int id = int.Parse(Request.Form["id"]);
            string commandName = Request.Form["cmdName"];
            var model = _article.GetModel(id);
            switch (commandName)
            {
                case "lbtnIsMsg":
                    if (model.is_msg == 1)
                        _article.UpdateField(id, "is_msg=0");
                    else
                        _article.UpdateField(id, "is_msg=1");
                    break;
                case "lbtnIsTop":
                    if (model.is_top == 1)
                        _article.UpdateField(id, "is_top=0");
                    else
                        _article.UpdateField(id, "is_top=1");
                    break;
                case "lbtnIsRed":
                    if (model.is_red == 1)
                        _article.UpdateField(id, "is_red=0");
                    else
                        _article.UpdateField(id, "is_red=1");
                    break;
                case "lbtnIsHot":
                    if (model.is_hot == 1)
                        _article.UpdateField(id, "is_hot=0");
                    else
                        _article.UpdateField(id, "is_hot=1");
                    break;
                case "lbtnIsSlide":
                    if (model.is_slide == 1)
                        _article.UpdateField(id, "is_slide=0");
                    else
                        _article.UpdateField(id, "is_slide=1");
                    break;
            }
            return Content("1");
        }

        //保存排序
        [HttpPost]
        public async Task<ActionResult> SubmitSave()
        {
            ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                int sortId = int.Parse(item["sortId"].ToString());
                _article.UpdateField(id, "sort_id=" + sortId.ToString());
            }
            await AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "保存内容排序"); //记录日志
            string script = JscriptMsg("保存排序成功！", Utils.CombUrlTxt("index", "channel_id={0}&category_id={1}&keywords={2}&property={3}",
                this.channel_id.ToString(), this.category_id.ToString(), this.keywords, this.property));
            return Content(script);
        }

        //批量删除
        [HttpPost]
        public async Task<ActionResult> SubmitDelete()
        {
            ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                if (_article.Delete(id,sysConfig,_env.ContentRootPath))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            await AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "删除内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "channel_id={0}&category_id={1}&keywords={2}&property={3}",
                this.channel_id.ToString(), this.category_id.ToString(), this.keywords, this.property));
            return Content(script);
        }

        //批量审核
        [HttpPost]
        public async Task<ActionResult> SubmitAudit()
        {
            ChkAdminLevel("article_" + this.channel_id + "_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken list = jobject["list"];
            foreach (JToken item in list)
            {
                int id = int.Parse(item["id"].ToString());
                _article.UpdateField(id, "status=0");
            }

            await AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "审核内容信息"); //记录日志
            string script = JscriptMsg("批量审核成功！", Utils.CombUrlTxt("index", "channel_id={0}&category_id={1}&keywords={2}&property={3}",
                this.channel_id.ToString(), this.category_id.ToString(), this.keywords, this.property));
            return Content(script);
        }

        #region 绑定类别=================================
        private void TreeBind()
        {
            var dt = _article_category.GetList(0,this.channel_id);
            List<SelectListItem> categoryListItems = new List<SelectListItem>() {
              new SelectListItem(){ Text="所有类别", Value=""}
           };
            List<SelectListItem> moveListItems = new List<SelectListItem>() {
            new SelectListItem(){ Text="批量移动...", Value=""}
         };
            foreach (Article_category dr in dt)
            {
                string Id = dr.id.ToString();
                int ClassLayer = dr.class_layer;
                string Title = dr.title;

                if (ClassLayer == 1)
                {
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                    moveListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                    moveListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            ViewData["categoryListItems"] = categoryListItems;
            ViewData["moveListItems"] = moveListItems;

            // 
            List<SelectListItem> propertyList = new List<SelectListItem>(){
              new SelectListItem(){ Text = "所有属性", Value = ""},
              new SelectListItem(){ Text = "待审核", Value = "isLock"},
              new SelectListItem(){ Text = "已审核", Value = "unIsLock"},
              new SelectListItem(){ Text = "可评论", Value = "isMsg"},
              new SelectListItem(){ Text = "置顶", Value = "isTop"},
              new SelectListItem(){ Text = "推荐", Value = "idRed"},
              new SelectListItem(){ Text = "热门", Value = "isHot"},
              new SelectListItem(){ Text = "幻灯片", Value = "isSlide"},
           };
            ViewData["propertyList"] = propertyList;
        }
        #endregion

        #region 数据绑定=================================
        private void RptBind(int _category_id, string _strWhere, string _orderby)
        {

            //图表或列表显示
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _article.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _article.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("../article_list/index", "channel_id={0}&category_id={1}&keywords={2}&property={3}&page={4}",
                this.channel_id.ToString(), _category_id.ToString(), this.keywords, this.property, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();           
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and status=1");
                        break;
                    case "unIsLock":
                        strTemp.Append(" and status=0");
                        break;
                    case "isMsg":
                        strTemp.Append(" and is_msg=1");
                        break;
                    case "isTop":
                        strTemp.Append(" and is_top=1");
                        break;
                    case "isRed":
                        strTemp.Append(" and is_red=1");
                        break;
                    case "isHot":
                        strTemp.Append(" and is_hot=1");
                        break;
                    case "isSlide":
                        strTemp.Append(" and is_slide=1");
                        break;
                }
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回图文每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["article_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 替换内容图片路径=========================
        private string ReplaceImagesPath(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                //如果是本地图片，则加上http://网址/网站安装目录/上传目录/文件名
                if (imgUri.StartsWith("/" + sysConfig.filepath + "/"))
                {
                    string newImgPath = "https://" + Request.Host.Value.ToLower() + imgUri;
                    content = content.Replace(imgUri, newImgPath);
                }
            }
            return content;
        }
        #endregion
    }
}
